package com.wocai.jrt.orgadmin.product.action;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.message.service.spi.MessageLogService;
import com.wocai.jrt.orgadmin.product.model.InvestReport;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.service.spi.InvestReportService;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 投资报告控制器
 * 
 * @author yinlei
 * @date 2015-12-7 17:53:15
 */
@Controller
@RequestMapping("/investReport")
public class InvestReportAction extends GenericAction<InvestReport> {
	private static final Logger LOGGER = LoggerFactory.getLogger(InvestReportAction.class);

	@Inject
	private InvestReportService investReportServiceImpl;
	@Inject
	private ProductService productServiceImpl;
	@Inject
	private MessageLogService messageLogServiceImpl;

	@RequestMapping("/report/{productId}")
	public String report(@PathVariable("productId") String productId, Map<String, Object> maps) {
		Product product = productServiceImpl.get(productId);
		maps.put("product", product);
		return "product/report";
	}

	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody InvestReport model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request product report, param = [{}]", JSON.toJSONString(model));
			int size = investReportServiceImpl.countBy(model);

			if (model.getPageSize() == -1) {
				model.setStart(null);
			}

			model.setOrderBy("upload_time desc");
			List<InvestReport> list = investReportServiceImpl.pagedList(model);

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request product report error, msg = [{}]", e.getMessage());
		}

		return map;
	}

	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(InvestReport model) {
		JsonBean jsonBean = new JsonBean();
		try {
			MultipartFile report = model.getReport();
			String rename = model.getRename();

			if (null == report || StringUtils.isBlank(model.getProductId())) {
				jsonBean.setMessage("param is error");
				return jsonBean;
			}

			String reportFilePath = MyFileUtils.uploadFile(report, MyFileUtils.FILE_TYPE);

			model.setId(ObjectId.get().toString());
			model.setOrgId(UserUtils.getUser().getOrgId());
			model.setUploadTime(new Date());

			File reportFile = new File(reportFilePath);
			if (StringUtils.isNotBlank(rename)) {
				rename = rename.replace(".pdf", "").replace(".docx", "").replace(".doc", "");
				File renameFile = new File(reportFile.getPath().replace(
						reportFile.getName().split("\\.")[0], rename));
				reportFile.renameTo(renameFile);

				model.setFileName(renameFile.getName());
				model.setFilePath(renameFile.getPath());
			} else {
				model.setFileName(reportFile.getName());
				model.setFilePath(reportFile.getPath());
			}

			int result = investReportServiceImpl.save(model);
			if (result == 1) {
				jsonBean.setMessage(SUCCESS);
				jsonBean.setCode(1);
				LOGGER.info("save record success.");
				
				//发送投后报告成功,向购买该产品的投后用户发送推送消息
				try {
					messageLogServiceImpl.productInvestReportMessage(model);
				} catch (Exception e) {
					LOGGER.error("send message for productInvestReportMessage error,errorMsg=[{}].",e.getMessage());
				}
				
			} else {
				jsonBean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}

			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			jsonBean.setMessage(ERROR);
		}

		return jsonBean;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		JsonBean bean = new JsonBean();
		try {
			int result = investReportServiceImpl.deleteById(id);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	@ResponseBody
	@RequestMapping("/downloadFile")
	public JsonBean downloadFile(String id, HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 发起请求的参数
			LOGGER.info("request file download, id=[{}]", id);

			String filePath = investReportServiceImpl.get(id).getFilePath();
			MyFileUtils.downloadFile(filePath, response);

			// 封装jsonBean
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

		} catch (Exception e) {
			LOGGER.error("download file error, error=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("download file error");
		}

		return jsonBean;
	}
}
